<?php

/*
  Aurus CMS - free OOP CMS
  Copyright (C) 2010  Nestor Yanchuk

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class Controller implements Core {
	
	/**
	 * Return an instance of class
	 *
	 * @return Controller
	 */
	public static function getInstance() {
		return Factory::get(__CLASS__);
	}
	
	public static function run() {
		$self = self::getInstance();
		$self->includeJs();
		$self->loadModules();
		
		if (IN_ADMIN) {
			return $self->initAdmin();
		}
		
		$self->start();
		
		if (! AJAX) {
			$self->end();
		}
	}
	
	public function initAdmin() {
		Adminarea::getInstance()->init();
	}
	
	public function includeJs() {
		Aurus::getInstance()->includeJs(LINK_ROOT . 'scripts/jquery.js');
		Aurus::getInstance()->includeJs(LINK_ROOT . 'language/' . Config::get('language') . '/lang.js');
		Aurus::getInstance()->includeJs(LINK_ROOT . 'scripts/functions.js');
		Aurus::getInstance()->addJs('template = "' . Aurus::getInstance()->getTemplateToLoad() . '";');
		Aurus::getInstance()->addJs('link_root = "' . LINK_ROOT . '";');
	}
	
	public function loadModules() {
		$ains = Modules::getInstance()->getActiveAddons();
		
		// Detecting text editors(bbcodes, wysiwyg, etc..)
		for($___ = 0, $n = count($ains['editors']); $___ < $n; $___ ++) {
			include (MAINDIR . '/editors/' . $ains['editors'][$___] . '/index.php');
		}
		
		//Detecting plugins
		include MAINDIR . '/interfaces/plugin.php';
		for($___ = 0, $n = count($ains['plugins']); $___ < $n; $___ ++) {
			$class = 'Plugin_' . substr($ains['plugins'][$___], 0, - 4);
			if (Aurus::getInstance()->is_plugin($class)) {
				Factory::runStatic($class, 'run');
			}
		}
		
		// Detecting modules
		for($___ = 0, $n = count($ains['modules']); $___ < $n; $___ ++) {
			include (MAINDIR . '/modules/' . $ains['modules'][$___] . '/index.php');
		}
		
		if (IN_ADMIN) {
			$rd = read_directory(MAINDIR . '/classes/');
			foreach ( $rd as $class ) {
				if (is_file($file = MAINDIR . '/classes/' . $class . '/index.php')) {
					include ($file);
				}
			}
		}
	}
	
	public function start() {
		include MAINDIR . '/interfaces/module.php';
		Modules::getInstance()->loadModule(Modules::getInstance()->getModuleToLoad());
		Aurus::getInstance()->addCronJob(array ('Cache', 'clear'));
	}
	
	public function end() {
		Aurus::getInstance()->addMeta('<title>' . Aurus::getInstance()->getTitle() . '</title>' . RN);
		Aurus::getInstance()->addMeta('<meta http-equiv="content-type" content="text/html; charset=UTF-8" />' . RN);
		Aurus::getInstance()->addMeta('<meta name="keywords" content="' . Aurus::getInstance()->getKeyWords() . '" />' . RN);
		Aurus::getInstance()->addMeta('<meta name="description" content="' . Config::get('siteDesc') . '" />' . RN);
		Aurus::getInstance()->addMeta(Config::get('metadata'));
		
		$tpl = Template::getInstance();
		
		$info = '';
		$errors = '';
		
		if (sizeof(Aurus::getInstance()->getErrors())) {
			if (Aurus::getInstance()->getContent() == '' && !sizeof(Aurus::getInstance()->getErrors())){
				Aurus::getInstance()->setError(__('Такої сторінки не існує, або вона була видалена'));
			}
	
			$tpl->load('errors');
			$tpl->set('{errors}', implode('<br/>', Aurus::getInstance()->getErrors()));
			$errors = $tpl->out();

		}
		if (sizeof(Aurus::getInstance()->getInfo())) {
			$tpl->load('info');
			$tpl->set('{info}', implode('<br/>', Aurus::getInstance()->getInfo()));
			$info = $tpl->out();
		}
		
		$tpl->load('main');
		$tpl->set('{content}', Aurus::getInstance()->getContent());
		$tpl->set('{scripts}', Aurus::getInstance()->getClientJs());
		$tpl->set('{head}', Aurus::getInstance()->getMeta());
		
		$tpl->set('{messages}', $errors . $info);
	
		
		$tpl->set('{LINK_ROOT}', LINK_ROOT);
		$tpl->set('{THEME}', LINK_ROOT . 'templates/' . Aurus::getInstance()->getTemplateToLoad());
		
		$out = filter($tpl->out(), 'page');
		
		if (DEV_MODE) {
			$this->_print($out . $this->info());
		} else {
			$this->_print($out);
		}
	}
	
	public function info() {
		$mem = formatFileSize(memory_get_usage() - START_MEMORY);
		$time = round(microtime(true) - START_TIME, 6);
		return RN . '<!-- ' . RN . 'Exegution time: ' . $time . RN . 'Memory usage: ' . $mem . RN . 'MySQL queries count:' . Mysql::getInstance()->getQueryCount() . RN . RN . 'MySQL queries:' . str_replace('-', ' -', RN . '-' . implode(RN . '-', Mysql::getInstance()->getQueries()) . RN) . '-->';
	}
	
	public function _print($echo) {
		if (DEV_MODE or ! boolean(Config::get('gzip')) or ! $echo or ! function_exists('gzencode')) {
			echo $echo;
			return;
		}
		if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false) {
			$enc = "x-gzip";
		} else {
			$enc = false;
		}
		if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
			$enc = "gzip";
		} else {
			$enc = false;
		}
		
		$level = ( int ) Config::get('gzipLevel');
		if ($level > 10 or $level < 1)
			$level = 3;
		
		if ($enc !== false) {
			header("Content-Encoding: $enc");
			header("Content-Length: " . strlen($cont = gzencode($echo, $level)));
			echo $cont;
		} else {
			header("Content-Length: " . strlen($echo));
			echo $echo;
		}
	}

}